<?php
// 添加或编辑记录组件
function renderAddEditRecord($conn, $edit_record = null) {
    // 获取默认值
    $default_question_type = get_most_used_question_type($conn);
    $default_chapter = get_latest_chapter($conn);
    $default_question_number = get_latest_question_number($conn);
    $default_exercise_set_id = get_latest_exercise_set($conn);
    
    // 获取习题集数据
    $sets_result = $conn->query("SELECT * FROM exercise_sets ORDER BY id");
    $chapters_by_set = [];
    
    // 获取章节数据
    $chapters_result = $conn->query("SELECT * FROM chapters ORDER BY exercise_set_id, id");
    while ($row = $chapters_result->fetch_assoc()) {
        if (!isset($chapters_by_set[$row['exercise_set_id']])) {
            $chapters_by_set[$row['exercise_set_id']] = [];
        }
        $chapters_by_set[$row['exercise_set_id']][] = $row;
    }
    
    // 获取最近5条添加的记录
    $latest_records = [];
    $sql = "SELECT er.*, c.name AS chapter_name, e.name AS exercise_set_name FROM exam_records er 
            LEFT JOIN chapters c ON er.chapter_id = c.id 
            LEFT JOIN exercise_sets e ON er.exercise_set_id = e.id 
            ORDER BY er.id DESC LIMIT 5";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $latest_records[] = $row;
    }
    $stmt->close();
    
    $formHtml = '    <div class="card">
            <div class="card-header">
                <h3>' . ($edit_record ? '编辑记录' : '添加记录') . '</h3>
            </div>
            <div class="card-body">';
    
    // 检查是否有重复记录错误
    if (isset($_GET['duplicate']) && $_GET['duplicate'] === 'true') {
        $formHtml .= '                <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <strong>错误：</strong> 该记录已存在，请不要重复添加！
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>';
    }
    
    $formHtml .= '                <form method="post" class="row g-3">
                    ' . ($edit_record ? '<input type="hidden" name="id" value="' . $edit_record['id'] . '">' : '');
    
    // 日期输入
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">日期 *</label>
                        <input type="date" name="exam_date" class="form-control" required value="' . ($edit_record ? $edit_record['exam_date'] : date('Y-m-d')) . '">
                    </div>';
    
    // 做题方式输入
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">做题方式 *</label>
                        <input type="text" name="question_type" class="form-control" required value="' . ($edit_record ? $edit_record['question_type'] : $default_question_type) . '" placeholder="' . ($default_question_type ? '如：' . htmlspecialchars($default_question_type) : '练习、模拟考试等') . '">
                    </div>';
    
    // 习题集选择
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">习题集 *</label>
                        <select name="exercise_set_id" id="exercise_set_id" class="form-control form-select shadow-none border border-gray-300 rounded-lg transition-all duration-200 focus:border-primary focus:ring-2 focus:ring-primary/20" required>';
    
    // 添加习题集选项
    $has_selected = false;
    if ($sets_result->num_rows > 0) {
        // 先添加禁用的请选择选项
        $formHtml .= '                            <option value="" disabled>请选择习题集</option>';
        while ($set = $sets_result->fetch_assoc()) {
            // 如果是编辑模式，使用编辑记录的值；否则使用默认值
            $selected = '';
            if ($edit_record && isset($edit_record['exercise_set_id']) && $edit_record['exercise_set_id'] == $set['id']) {
                $selected = 'selected';
                $has_selected = true;
            } else if (!$edit_record && $default_exercise_set_id == $set['id']) {
                $selected = 'selected';
                $has_selected = true;
            }
            $formHtml .= "                            <option value='{$set['id']}' {$selected}>{$set['name']}</option>";
        }
        // 如果没有选中任何项，添加选中的空选项
        if (!$has_selected) {
            $formHtml .= '                            <option value="" disabled selected>请选择习题集</option>';
        }
    } else {
        $formHtml .= '                            <option value="" disabled selected>请选择习题集</option>';
    }
    $formHtml .= '                        </select>
                    </div>';
    
    // 章节选择
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">章节 *</label>
                        <select name="chapter_id" id="chapter_id" class="form-control form-select shadow-none border border-gray-300 rounded-lg transition-all duration-200 focus:border-primary focus:ring-2 focus:ring-primary/20" required>';
    
    // 添加章节选项
    $formHtml .= '                            <option value="" disabled selected>请选择章节</option>';
    if ($edit_record && isset($edit_record['exercise_set_id']) && isset($chapters_by_set[$edit_record['exercise_set_id']])) {
        foreach ($chapters_by_set[$edit_record['exercise_set_id']] as $chapter) {
            $selected = ($edit_record && isset($edit_record['chapter_id']) && $edit_record['chapter_id'] == $chapter['id']) ? 'selected' : '';
            $formHtml .= "                            <option value='{$chapter['id']}' {$selected}>{$chapter['name']}</option>";
        }
    }
    $formHtml .= '                        </select>
                    </div>';
    
    // 题号输入
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">题号 *</label>
                        <input type="text" name="question_number" class="form-control" required value="' . ($edit_record ? $edit_record['question_number'] : $default_question_number) . '" placeholder="' . ($default_question_number ? '如：' . htmlspecialchars($default_question_number) : '1、2、3或A1、B2等') . '">
                    </div>';
    
    // 开始时间输入
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">做题开始时间 *</label>
                        <input type="time" name="start_time" id="start_time" class="form-control" required value="' . ($edit_record ? $edit_record['start_time'] : date('H:i')) . '">
                    </div>';
    
    // 结束时间输入
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">做题结束时间 *</label>
                        <input type="time" name="end_time" id="end_time" class="form-control" required value="' . ($edit_record ? $edit_record['end_time'] : date('H:i')) . '">
                    </div>';
    
    // 正确情况选择
    $formHtml .= '                    <div class="col-md-4">
                        <label class="form-label">正确情况</label>
                        <select name="correctness" class="form-control form-select shadow-none border border-gray-300 rounded-lg transition-all duration-200 focus:border-primary focus:ring-2 focus:ring-primary/20">
                            <option value="未批改"' . ($edit_record && $edit_record['correctness'] == '未批改' ? ' selected' : '') . '>未批改</option>
                            <option value="正确"' . ($edit_record && $edit_record['correctness'] == '正确' ? ' selected' : '') . '>正确</option>
                            <option value="错误"' . ($edit_record && $edit_record['correctness'] == '错误' ? ' selected' : '') . '>错误</option>
                            <option value="不完全正确"' . ($edit_record && $edit_record['correctness'] == '不完全正确' ? ' selected' : '') . '>不完全正确</option>
                        </select>
                    </div>';
    
    // 备注输入
    $formHtml .= '                    <div class="col-md-12">
                        <label class="form-label">备注</label>
                        <textarea name="notes" class="form-control" rows="2" placeholder="添加备注信息">' . ($edit_record ? $edit_record['notes'] : '') . '</textarea>
                    </div>
                    
                    <!-- 错因和反思字段 -->
                    <div class="col-md-6">
                        <label class="form-label">错因</label>
                        <textarea name="error_reason" class="form-control" rows="3" placeholder="记录错误原因">' . ($edit_record ? $edit_record['error_reason'] : '') . '</textarea>
                    </div>
                    
                    <div class="col-md-6">
                        <label class="form-label">反思</label>
                        <textarea name="reflection" class="form-control" rows="3" placeholder="记录学习反思">' . ($edit_record ? $edit_record['reflection'] : '') . '</textarea>
                    </div>';
    
    // 提交按钮
    $formHtml .= '                    <div class="col-12">
                        <button type="submit" name="' . ($edit_record ? 'update_record' : 'add_record') . '" class="btn btn-primary">' . ($edit_record ? '更新记录' : '添加记录') . '</button>
                        ' . ($edit_record ? '<a href="index.php" class="btn btn-secondary ms-2">取消编辑</a>' : '') . '
                    </div>
                </form>';
    
    // 最近添加的记录
    if (!empty($latest_records)) {
        $formHtml .= '                <div class="mt-5">
                    <h5>最近添加的记录</h5>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                <th>日期</th>
                                <th>做题方式</th>
                                <th>习题集</th>
                                <th>章节</th>
                                <th>题号</th>
                                <th>做题时间</th>
                                <th>耗时(分钟)</th>
                            </tr>
                            </thead>
                            <tbody>';
        
        foreach ($latest_records as $record) {
            $formHtml .= '                                <tr>
                                    <td>' . $record['exam_date'] . '</td>
                                    <td>' . $record['question_type'] . '</td>
                                    <td>' . ($record['exercise_set_name'] ?? '') . '</td>
                                    <td>' . ($record['chapter_name'] ?? '') . '</td>
                                    <td>' . $record['question_number'] . '</td>
                                    <td>' . ($record['start_time'] ?? '') . ' - ' . ($record['end_time'] ?? '') . '</td>
                                    <td>' . ($record['duration'] ?? '') . '</td>
                                </tr>';
        }
        
        $formHtml .= '                            </tbody>
                        </table>
                    </div>
                </div>';
    }
    
    $formHtml .= '            </div>
        </div>';
    
    // 添加JavaScript处理习题集和章节的联动
    $formHtml .= '<script>
    // 章节数据
    const chaptersBySet = ' . json_encode($chapters_by_set) . ';
    // 默认章节
    const defaultChapter = "' . ($default_chapter ? addslashes($default_chapter) : '') . '";
    
    // 习题集改变时更新章节选项
    function updateChapterOptions(selectedSetId) {
        const chapterSelect = document.getElementById("chapter_id");
        
        // 清空章节选项
        chapterSelect.innerHTML = "<option value=\"\" disabled>请选择章节</option>";
        let hasSelected = false;
        
        // 如果选择了习题集，添加对应的章节选项
        if (selectedSetId && chaptersBySet[selectedSetId]) {
            chaptersBySet[selectedSetId].forEach(function(chapter) {
                const option = document.createElement("option");
                option.value = chapter.id;
                option.textContent = chapter.name;
                // 如果是默认章节，自动选中
                if (defaultChapter && chapter.name === defaultChapter && !hasSelected) {
                    option.selected = true;
                    hasSelected = true;
                }
                chapterSelect.appendChild(option);
            });
            
            // 如果没有选中默认章节，选中第一个选项
            if (!hasSelected && chapterSelect.options.length > 1) {
                chapterSelect.options[1].selected = true;
            }
        } else if (!hasSelected) {
            // 如果没有选择习题集且没有选中任何选项，添加默认选中的空选项
            chapterSelect.innerHTML += "<option value=\"\" disabled selected>请选择章节</option>";
        }
    }
    
    // 添加事件监听器
    document.getElementById("exercise_set_id").addEventListener("change", function() {
        updateChapterOptions(this.value);
    });
    
    // 页面加载时，检查是否有默认习题集，如果有则加载对应的章节
    document.addEventListener("DOMContentLoaded", function() {
        const exerciseSetSelect = document.getElementById("exercise_set_id");
        if (exerciseSetSelect.value) {
            updateChapterOptions(exerciseSetSelect.value);
        }
    });
    </script>';
    
    // 添加成功提示模态框的HTML结构
    $formHtml .= '<!-- 添加成功提示模态框 -->
    <div id="addSuccessModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="addSuccessModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addSuccessModalLabel">添加成功</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>记录已成功添加到数据库。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="addAnotherRecordBtn">继续添加</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 重复数据提示模态框 -->
    <div id="duplicateRecordModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="duplicateRecordModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title" id="duplicateRecordModalLabel">数据重复</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="text-danger">警告：您正在添加的记录与现有记录重复！</p>
                    <p>请检查日期、习题集、章节和题号是否已存在。</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">确认</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 模态框相关JavaScript -->
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        var urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get("added") === "true") {
            $("#addSuccessModal").modal("show");
            window.history.replaceState({}, document.title, window.location.pathname + "?tab=add");
        }
        
        // 继续添加按钮点击事件
        $("#addAnotherRecordBtn").on("click", function() {
            $("#addSuccessModal").modal("hide");
            // 重置表单但保留日期和做题方式
            var form = document.querySelector("form");
            var dateValue = form.elements["exam_date"].value;
            var questionTypeValue = form.elements["question_type"].value;
            form.reset();
            form.elements["exam_date"].value = dateValue;
            form.elements["question_type"].value = questionTypeValue;
            // Focus on the first input field
            form.elements["exam_date"].focus();
        });
        
        // 表单提交前检查重复数据
        var formCheck = document.querySelector("form");
        if (formCheck && !formCheck.elements["id"]) { // 只有在添加模式下检查重复
            // Use named function instead of arguments.callee
            function handleSubmit(event) {
                // Validate required fields
                var requiredFields = ["exam_date", "question_type", "exercise_set_id", "chapter_id", "question_number", "start_time", "end_time"];
                var isValid = true;
                
                for(var i=0; i<requiredFields.length; i++) {
                    var fieldName = requiredFields[i];
                    var field = formCheck.elements[fieldName];
                    if (!field || !field.value.trim()) {
                        isValid = false;
                    }
                }
                
                if (!isValid) {
                    alert("Please fill all required fields");
                    event.preventDefault();
                    return;
                }
                
                event.preventDefault();
                
                var formData = new FormData();
                formData.append("check_duplicate", "true");
                formData.append("exam_date", formCheck.elements["exam_date"].value);
                formData.append("question_type", formCheck.elements["question_type"].value);
                formData.append("exercise_set_id", formCheck.elements["exercise_set_id"].value);
                formData.append("chapter_id", formCheck.elements["chapter_id"].value);
                formData.append("question_number", formCheck.elements["question_number"].value);
                formData.append("start_time", formCheck.elements["start_time"].value);
                formData.append("end_time", formCheck.elements["end_time"].value);
                
                // Simplified fetch request
                var xhr = new XMLHttpRequest();
                xhr.open("POST", "index.php", true);
                xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                
                xhr.onload = function() {
                    var data = { is_duplicate: false };
                    try {
                        data = JSON.parse(xhr.responseText);
                    } catch(e) {
                        // Invalid JSON
                    }
                    
                    // Check for duplicate
                    if (data.is_duplicate) {
                        // Show duplicate warning with confirmation
                        var proceed = confirm("Warning: Duplicate record detected!\n\nThis record appears to be a duplicate of an existing record.\n\nDo you still want to add this record?");
                        
                        if (!proceed) {
                            // User chose not to proceed with duplicate
                            return;
                        }
                    }
                    
                    // If no duplicate or user confirmed to proceed, submit form
                    formCheck.removeEventListener("submit", handleSubmit);
                    formCheck.submit();
                };
                
                xhr.onerror = function() {
                    // On error, submit form anyway
                    formCheck.removeEventListener("submit", handleSubmit);
                    formCheck.submit();
                };
                
                xhr.send(formData);
            }
            
            // Add event listener
            formCheck.addEventListener("submit", handleSubmit);
        }
    });
    </script>';
    
    return $formHtml;
}